const Post = require('../models/post');

// 创建新帖子
exports.createPost = async (req, res) => {
    try {
        const {
            title,
            content,
            post_type,
            category,
            image_urls,
            video_url,
            tags
        } = req.body;

        // 验证必填字段
        if (!title || !content || !post_type || !category) {
            return res.status(400).json({
                success: false,
                message: '标题、内容、帖子类型和分类为必填项'
            });
        }

        // 验证帖子类型
        const validPostTypes = ['攻略', '讨论', '视频', '资讯'];
        if (!validPostTypes.includes(post_type)) {
            return res.status(400).json({
                success: false,
                message: '无效的帖子类型'
            });
        }

        // 验证分类
        const validCategories = ['角色', '装备', '副本', '剧情'];
        if (!validCategories.includes(category)) {
            return res.status(400).json({
                success: false,
                message: '无效的分类'
            });
        }

        // 创建帖子数据
        const postData = {
            title: title.trim(),
            content: content.trim(),
            post_type,
            category,
            user_id: req.user.id,
            image_urls: image_urls || [],
            video_url: video_url || null,
            tags: tags || null
        };

        // 创建帖子
        const postId = await Post.create(postData);

        res.status(201).json({
            success: true,
            message: '帖子发布成功',
            data: {
                post_id: postId
            }
        });
    } catch (error) {
        console.error('创建帖子失败:', error);
        res.status(500).json({
            success: false,
            message: '发布帖子失败，请稍后重试'
        });
    }
};

// 获取帖子列表
exports.getPosts = async (req, res) => {
    try {
        const {
            page = 1,
            limit = 10,
            sort = 'latest',
            post_type,
            category,
            search
        } = req.query;

        console.log('接收到的查询参数:', req.query);

        // 构建查询选项，确保类型正确
        const options = {
            page: parseInt(page) || 1,
            limit: parseInt(limit) || 10,
            sort: sort === 'hot' ? 'hot' : sort === 'comments' ? 'comments' : sort === 'likes' ? 'likes' : 'create_time',
            post_type: post_type || null,
            category: category || null,
            search: search || null
        };

        console.log('传递给模型的选项:', options);

        // 获取帖子列表
        const result = await Post.getPosts(options);

        // 返回完整的帖子信息
        const posts = result.posts.map(post => ({
            post_id: post.post_id,
            title: post.title,
            content: post.content,
            post_type: post.post_type,
            category: post.category,
            like_count: post.like_count,
            comment_count: post.comment_count,
            view_count: post.view_count,
            create_time: post.create_time,
            author: {
                user_id: post.user_id,
                nickname: post.author_name,
                avatar: post.author_avatar
            }
        }));

        res.json({
            success: true,
            data: posts,
            total: result.total,
            page: result.page,
            totalPages: result.totalPages
        });
    } catch (error) {
        console.error('获取帖子列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取帖子列表失败'
        });
    }
};

// 搜索帖子
exports.searchPosts = async (req, res) => {
    try {
        const {
            search,
            search_title = '1',
            search_content = '1',
            page = 1,
            limit = 10,
            sort = 'latest',
            post_type,
            category
        } = req.query;

        console.log('搜索参数:', req.query);

        // 验证搜索关键词
        if (!search || search.trim() === '') {
            return res.status(400).json({
                success: false,
                message: '搜索关键词不能为空'
            });
        }

        // 验证搜索范围
        if (search_title !== '1' && search_content !== '1') {
            return res.status(400).json({
                success: false,
                message: '请至少选择一个搜索范围'
            });
        }

        // 构建搜索选项
        const options = {
            page: parseInt(page) || 1,
            limit: parseInt(limit) || 10,
            sort: sort === 'hot' ? 'hot' : sort === 'comments' ? 'comments' : sort === 'likes' ? 'likes' : 'create_time',
            post_type: post_type || null,
            category: category || null,
            search: search.trim(),
            search_title: search_title === '1',
            search_content: search_content === '1'
        };

        console.log('搜索选项:', options);

        // 执行搜索
        const result = await Post.searchPosts(options);

        // 处理搜索结果
        const posts = result.posts.map(post => ({
            post_id: post.post_id,
            title: post.title,
            content: post.content,
            post_type: post.post_type,
            category: post.category,
            like_count: post.like_count,
            comment_count: post.comment_count,
            view_count: post.view_count,
            create_time: post.create_time,
            author: {
                user_id: post.user_id,
                nickname: post.author_name,
                avatar: post.author_avatar
            }
        }));

        res.json({
            success: true,
            data: posts,
            total: result.total,
            page: result.page,
            totalPages: result.totalPages
        });
    } catch (error) {
        console.error('搜索帖子失败:', error);
        res.status(500).json({
            success: false,
            message: '搜索失败，请稍后重试'
        });
    }
};

// 获取帖子详情
exports.getPostById = async (req, res) => {
    try {
        const { postId } = req.params;

        // 获取帖子详情
        const post = await Post.getPostById(postId);

        if (!post) {
            return res.status(404).json({
                success: false,
                message: '帖子不存在'
            });
        }

        // 增加浏览量
        await Post.incrementViewCount(postId);

        // 处理帖子数据
        const postData = {
            post_id: post.post_id,
            title: post.title,
            content: post.content,
            post_type: post.post_type,
            category: post.category,
            view_count: post.view_count + 1, // 实时显示增加后的浏览量
            like_count: post.like_count,
            comment_count: post.comment_count,
            is_top: post.is_top,
            is_精华: post.is_精华,
            image_urls: post.image_urls,
            video_url: post.video_url,
            tags: post.tags,
            create_time: post.create_time,
            update_time: post.update_time,
            author: {
                user_id: post.user_id,
                nickname: post.author_name,
                avatar: post.author_avatar,
                level: post.author_level
            }
        };

        res.json({
            success: true,
            data: postData
        });
    } catch (error) {
        console.error('获取帖子详情失败:', error);
        res.status(500).json({
            success: false,
            message: '获取帖子详情失败'
        });
    }
};

// 点赞帖子
exports.likePost = async (req, res) => {
    try {
        const { postId } = req.params;
        const userId = req.user.id;

        console.log('点赞请求 - 帖子ID:', postId, '用户ID:', userId);

        // 检查帖子是否存在
        const post = await Post.getPostById(postId);
        if (!post) {
            console.log('帖子不存在:', postId);
            return res.status(404).json({
                success: false,
                message: '帖子不存在'
            });
        }

        // 执行点赞操作
        const result = await Post.toggleLike(postId, userId);
        console.log('点赞操作结果:', result);

        const responseData = {
            success: true,
            message: '点赞成功',
            data: {
                action: result.action,
                likeCount: result.likeCount
            }
        };

        console.log('返回响应数据:', responseData);
        res.json(responseData);
    } catch (error) {
        console.error('点赞失败:', error);
        res.status(500).json({
            success: false,
            message: '点赞失败，请稍后重试'
        });
    }
};

// 删除帖子
exports.deletePost = async (req, res) => {
    try {
        const { postId } = req.params;
        const userId = req.user.id;

        // 删除帖子
        const deleted = await Post.deletePost(postId, userId);

        if (!deleted) {
            return res.status(404).json({
                success: false,
                message: '帖子不存在或无权限删除'
            });
        }

        res.json({
            success: true,
            message: '帖子删除成功'
        });
    } catch (error) {
        console.error('删除帖子失败:', error);
        res.status(500).json({
            success: false,
            message: '删除帖子失败，请稍后重试'
        });
    }
};

// 更新帖子
exports.updatePost = async (req, res) => {
    try {
        const { postId } = req.params;
        const userId = req.user.id;
        const {
            title,
            content,
            post_type,
            category,
            image_urls,
            video_url,
            tags
        } = req.body;

        // 验证必填字段
        if (!title || !content || !post_type || !category) {
            return res.status(400).json({
                success: false,
                message: '标题、内容、帖子类型和分类为必填项'
            });
        }

        // 更新数据
        const updateData = {
            title: title.trim(),
            content: content.trim(),
            post_type,
            category,
            image_urls: image_urls || [],
            video_url: video_url || null,
            tags: tags || null
        };

        // 更新帖子
        const updated = await Post.updatePost(postId, userId, updateData);

        if (!updated) {
            return res.status(404).json({
                success: false,
                message: '帖子不存在或无权限编辑'
            });
        }

        res.json({
            success: true,
            message: '帖子更新成功'
        });
    } catch (error) {
        console.error('更新帖子失败:', error);
        res.status(500).json({
            success: false,
            message: '更新帖子失败，请稍后重试'
        });
    }
};

// 获取用户帖子
exports.getUserPosts = async (req, res) => {
    try {
        const userId = req.user.id;
        const {
            page = 1,
            limit = 10,
            sort = 'latest'
        } = req.query;

        console.log('获取用户帖子，用户ID:', userId);

        // 构建查询选项
        const options = {
            page: parseInt(page) || 1,
            limit: parseInt(limit) || 10,
            sort: sort === 'hot' ? 'hot' : sort === 'comments' ? 'comments' : sort === 'likes' ? 'likes' : 'create_time',
            user_id: userId
        };

        console.log('用户帖子查询选项:', options);

        // 获取用户帖子列表
        const result = await Post.getUserPosts(options);

        // 返回完整的帖子信息
        const posts = result.posts.map(post => ({
            post_id: post.post_id,
            title: post.title,
            content: post.content,
            post_type: post.post_type,
            category: post.category,
            like_count: post.like_count,
            comment_count: post.comment_count,
            view_count: post.view_count,
            create_time: post.create_time,
            author: {
                user_id: post.user_id,
                nickname: post.author_name,
                avatar: post.author_avatar
            }
        }));

        res.json({
            success: true,
            data: posts,
            total: result.total,
            page: result.page,
            totalPages: result.totalPages
        });
    } catch (error) {
        console.error('获取用户帖子失败:', error);
        res.status(500).json({
            success: false,
            message: '获取用户帖子失败'
        });
    }
}; 